#!/bin/bash
# 简化的WeBASE零知识证明验证测试
# 合约地址: 0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf

echo "🚀 测试WeBASE零知识证明验证..."
echo "合约地址: 0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf"
echo ""

# 1. 检查WeBASE服务
echo "检查WeBASE服务..."
if curl -s --max-time 5 http://localhost:5002/WeBASE-Front/monitor > /dev/null 2>&1; then
    echo "✅ WeBASE服务运行正常"
else
    echo "❌ WeBASE服务不可达"
    exit 1
fi

# 2. 获取编码的proof数据
echo "获取ABI编码数据..."
if [ -f "abi_encoded_proof.json" ]; then
    PACKED_PROOF=$(cat abi_encoded_proof.json | grep -o '"packedProof":"[^"]*"' | cut -d'"' -f4)
    echo "✅ 已获取800字节ABI编码数据"
    echo "数据长度: ${#PACKED_PROOF} 字符"
else
    echo "❌ 缺少abi_encoded_proof.json文件"
    exit 1
fi

# 3. 执行WeBASE调用
echo ""
echo "执行WeBASE调用..."

RESPONSE=$(curl -s -X POST \
  -H "Content-Type: application/json" \
  --data "{
    \"abiInfo\": [
        {
            \"inputs\": [{\"name\": \"packedProof\", \"type\": \"bytes\"}],
            \"name\": \"verifyAssetZKPacked\", 
            \"outputs\": [{\"name\": \"\", \"type\": \"bool\"}],
            \"stateMutability\": \"nonpayable\",
            \"type\": \"function\"
        }
    ],
    \"contractAddress\": \"0x1d38f5d0c8c1ae7ed63a2d0ec905b9e9a17e70cf\",
    \"funcName\": \"verifyAssetZKPacked\",
    \"funcParam\": [\"$PACKED_PROOF\"],
    \"groupId\": 1,
    \"signUserId\": \"user1001\"
}" \
http://localhost:5002/WeBASE-Front/trans/handle)

# 4. 分析响应
echo "响应结果:"
echo "$RESPONSE"
echo ""

# 5. 简单分析
if echo "$RESPONSE" | grep -q "\"code\":0"; then
    echo "✅ API调用成功"
    
    # 提取交易哈希
    TX_HASH=$(echo "$RESPONSE" | grep -o '"data":"[^"]*"' | cut -d'"' -f4)
    if [ -n "$TX_HASH" ] && [ "$TX_HASH" != "null" ]; then
        echo "🔗 交易哈希: $TX_HASH"
        
        # 等待交易确认
        echo "⏳ 等待3秒后查询交易回执..."
        sleep 3
        
        # 查询交易回执
        RECEIPT=$(curl -s -X POST \
          -H "Content-Type: application/json" \
          --data "{
            \"jsonrpc\": \"2.0\",
            \"method\": \"getTransactionReceipt\",
            \"params\": [1, \"$TX_HASH\"],
            \"id\": 1
          }" \
        http://localhost:5002/WeBASE-Front/web3/jsonrpc)
        
        echo "交易回执:"
        echo "$RECEIPT"
        
        # 检查交易状态
        if echo "$RECEIPT" | grep -q '"status":"0x0"'; then
            echo ""
            echo "✅ 交易执行成功!"
            
            # 检查输出值
            if echo "$RECEIPT" | grep -q '"output":".*1"'; then
                echo "🎉 零知识证明验证成功! (返回true)"
            elif echo "$RECEIPT" | grep -q '"output":".*0"'; then
                echo "❌ 零知识证明验证失败 (返回false)"
            else
                echo "🔍 需要进一步分析输出值"
            fi
        else
            echo "❌ 交易执行失败"
        fi
    fi
elif echo "$RESPONSE" | grep -q "error"; then
    echo "❌ API调用失败，存在错误"
else
    echo "⚠️  响应格式未知"
fi

echo ""
echo "测试完成!" 